<template>
  <div class="community-page">
    <div class="page-header">
      <h2>育儿社区</h2>
      <el-button type="primary" @click="handleCreatePost">
        发帖
      </el-button>
    </div>

    <!-- 帖子类型过滤 -->
    <div class="filter-section">
      <el-radio-group v-model="activeType" @change="handleTypeChange">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button :label="1">经验分享</el-radio-button>
        <el-radio-button :label="2">提问求助</el-radio-button>
        <el-radio-button :label="3">热门话题</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 帖子列表 -->
    <div class="post-list" v-loading="loading">
      <el-card v-for="post in postList" :key="post.id" class="post-card">
        <div class="post-header">
          <div class="user-info">
            <el-avatar :size="40" :src="post.userAvatar" />
            <span class="username">{{ post.username }}</span>
          </div>
          <el-tag :type="getPostTypeTag(post.postType)">
            {{ postTypeMap[post.postType] }}
          </el-tag>
        </div>

        <div class="post-content" @click="handleViewPost(post)">
          <h3 class="post-title">{{ post.title }}</h3>
          <p class="post-text">{{ post.content }}</p>
        </div>

        <div class="post-footer">
          <div class="post-stats">
            <span class="stat-item">
              <el-icon><View /></el-icon>
              {{ post.viewCount }}
            </span>
            <span class="stat-item">
              <el-icon><ChatRound /></el-icon>
              {{ post.commentCount }}
            </span>
            <span class="stat-item" @click="handleLike(post)">
              <el-icon :class="{ 'liked': post.isLiked }">
                <StarFilled v-if="post.isLiked" />
                <Star v-else />
              </el-icon>
              {{ post.likeCount }}
            </span>
          </div>
          <span class="post-time">{{ formatDate(post.createTime) }}</span>
        </div>
      </el-card>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 发帖对话框 -->
    <el-dialog
        v-model="postDialogVisible"
        title="发布帖子"
        width="50%"
        :close-on-click-modal="false"
    >
      <el-form
          ref="postFormRef"
          :model="{ title, content, postType }"
          :rules="postRules"
          label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input
              v-model="title"
              placeholder="请输入标题"
              maxlength="100"
              show-word-limit
              clearable
          />
        </el-form-item>

        <el-form-item label="类型" prop="postType">
          <el-select
              v-model="postType"
              placeholder="请选择帖子类型"
              style="width: 100%"
              clearable
          >
            <el-option
                v-for="(value, key) in postTypeMap"
                :key="key"
                :label="value"
                :value="Number(key)"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
              v-model="content"
              type="textarea"
              :rows="6"
              placeholder="请输入内容"
              maxlength="2000"
              show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="postDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitting" @click="submitPost">
            发布
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { View, ChatRound, Star, StarFilled } from '@element-plus/icons-vue'
import { getPostList, createPost, likePost, unlikePost } from '@/api/community'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'

const router = useRouter()

// 帖子类型映射
const postTypeMap = {
  0: '普通帖子',
  1: '经验分享',
  2: '提问求助',
  3: '热门话题'
}

// 列表数据
const loading = ref(false)
const activeType = ref('all')
const postList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 发帖对话框
const postDialogVisible = ref(false)
const submitting = ref(false)

// 分开定义表单字段
const title = ref('')
const content = ref('')
const postType = ref('')

// 表单校验规则
const postRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { max: 100, message: '标题长度不能超过100个字符', trigger: 'blur' }
  ],
  postType: [
    { required: true, message: '请选择帖子类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { max: 2000, message: '内容长度不能超过2000个字符', trigger: 'blur' }
  ]
}

// 获取帖子类型对应的标签类型
const getPostTypeTag = (type) => {
  const tagMap = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'primary'
  }
  return tagMap[type] || 'info'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '--'
  console.log('原始日期:', date)
  const formattedDate = dayjs(date).format('YYYY-MM-DD HH:mm:ss')
  console.log('格式化后:', formattedDate)
  return formattedDate
}

// 获取帖子列表
const fetchPostList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      type: activeType.value === 'all' ? null : activeType.value
    }
    const res = await getPostList(params)
    console.log('帖子列表数据:', res)
    if (res && Array.isArray(res.records)) {
      postList.value = res.records.map(post => ({
        ...post,
        createTime: post.createTime,
        updateTime: post.updateTime
      }))
      total.value = res.total
    }
  } catch (error) {
    console.error('获取帖子列表失败:', error)
    ElMessage.error('获取帖子列表失败')
  } finally {
    loading.value = false
  }
}

// 处理类型切换
const handleTypeChange = () => {
  currentPage.value = 1
  fetchPostList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchPostList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchPostList()
}

// 发帖相关
const postFormRef = ref(null)  // 添加表单引用

const handleCreatePost = () => {
  title.value = ''
  content.value = ''
  postType.value = ''
  postDialogVisible.value = true
}

const submitPost = async () => {
  if (!postFormRef.value) return

  // 表单验证
  await postFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息')
      return
    }

    submitting.value = true
    try {
      // 提交时组合数据
      const postData = {
        title: title.value,
        content: content.value,
        postType: postType.value
      }
      const res = await createPost(postData)
      if (res) {
        ElMessage.success('发布成功')
      }
    } catch (error) {
      console.error('发布失败:', error)
      ElMessage.error('发布失败')
    } finally {
      // 无论成功失败，都执行以下操作
      submitting.value = false
      // 关闭对话框
      postDialogVisible.value = false
      // 重置表单数据
      title.value = ''
      content.value = ''
      postType.value = ''
      // 刷新列表
      await fetchPostList()
    }
  })
}

// 查看帖子详情
const handleViewPost = (post) => {
  router.push(`/user/community/post/${post.id}`)
}

// 点赞/取消点赞
const handleLike = async (post) => {
  try {
    if (post.isLiked) {
      await unlikePost(post.id)
      post.likeCount--
    } else {
      await likePost(post.id)
      post.likeCount++
    }
    post.isLiked = !post.isLiked
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

onMounted(() => {
  fetchPostList()
})
</script>

<style scoped>
.community-page {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.filter-section {
  margin-bottom: 20px;
}

.post-list {
  margin-top: 20px;
}

.post-card {
  margin-bottom: 16px;
  transition: all 0.3s;
}

.post-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.username {
  font-size: 14px;
  color: #333;
}

.post-content {
  cursor: pointer;
}

.post-title {
  margin: 0 0 12px;
  font-size: 18px;
  color: #303133;
}

.post-text {
  margin: 0;
  color: #606266;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}

.post-footer {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.post-stats {
  display: flex;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
}

.stat-item:hover {
  color: #409eff;
}

.liked {
  color: #409eff;
}

.post-time {
  font-size: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}
</style> 